import React  from 'react';
import PropTypes from 'proptypes';
import DatabaseListItemMetatada from './database-list-item-metadata.jsx';
import DatabaseFilter from './database-filter.jsx';
import {Menu,MenuItem,MenuButton,SubMenu,ControlledMenu,useMenuState} from '@szhsin/react-menu';

const STYLE = {
  database: {
    fontSize: '0.85em',
    color: '#636363',
    wordBreak: 'break-all',
    cursor: 'default',
    // force menu item go over the parent padding
    // this way allows the whole line be clickable
    position: 'abosolute',
    margin: '-0.92857143em -1.14285714em',
    padding: '0.92857143em 1.14285714em',
    display: 'block',
  },
  activeDatabase: {
    backgroundColor: '#FFFAF3',
    boxShadow: '0 0 0 1px #C9BA9B inset,0 0 0 0 transparent',
  },
  loadedDatabase: {
    backgroundColor: '#F8FFFF',
  },
};
let contextMenu=null;
export default function DatabaseListItem(props){
  const [menuProps,toggleMenu]=useMenuState();
  const [state,setState]=React.useState({
    x:0,y:0,
    filter:"",
  });
  const  ref_filter=React.useRef(null);
  // React.useEffect(()=>{
  //   if (contextMenu ) {
  //     return;
  //   }


  //   // contextMenu = new Menu();
  //   // contextMenu.append(
  //   //   new MenuItem({
  //   //     label: 'Refresh Database',
  //   //     click:()=>{props.onRefreshDatabase(props.database);},
  //   //   })
  //   // );
  //   // contextMenu.append(
  //   //   new MenuItem({
  //   //     label: 'Show Database Diagram',
  //   //     click:()=>{props.onShowDiagramModal(props.database);},
  //   //   })
  //   // );
  // },[props.tables && props.views && props.functions && props.procedures]);

  const onContextMenu=(event)=> {
    event.preventDefault();
    if (contextMenu) {
      contextMenu.popup({ x: event.clientX, y: event.clientY });
    }
  }

  const onFilterChange=(value)=> {
    setState({ filter: value });
  }

  const onHeaderDoubleClick=(database)=> {
    if (!isMetadataLoaded(props)) {
      props.onSelectDatabase(database);
      return;
    }

    toggleCollapse();
  }

  const filterItems=(filterInput, items) =>{
    const regex = RegExp(filterInput, 'i');
    return items.filter(item => regex.test(`${item.schema}.${item.name}`));
  }

  const focus=()=> {
    // If search is toggled for certain database that is collapsed then toggle collapse.
    if (state.collapsed) {
      toggleCollapse();
    }

    ref_filter.current.focus();
  }

  const isMetadataLoaded=(props)=> {
    console.log("isMetadataLoaded==============");
    console.log(props);
    const { tables, views, functions, procedures } = props ;
    return tables && views && functions && procedures;
  }

  const toggleCollapse=()=> {
    setState({ collapsed: !state.collapsed });
  }

  const renderBody=(isMetadataLoad, isCurrentDB) =>{
    const { filter } = state;
    const {
      client,
      tables,
      columnsByTable,
      triggersByTable,
      indexesByTable,
      views,
      functions,
      procedures,
      database,
      onExecuteDefaultQuery,
      onExecuteEditTable,
      onSelectTable,
      onGetSQLScript,
    } = props;

    let filteredTables;
    let filteredViews;
    let filteredFunctions;
    let filteredProcedures;

    const cssStyleItems = {};
    if (state.collapsed || !isMetadataLoad) {
      cssStyleItems.display = 'none';
    } else {
      filteredTables = filterItems(filter, tables);
      filteredViews = filterItems(filter, views);
      filteredFunctions = filterItems(filter, functions);
      filteredProcedures = filterItems(filter, procedures);
    }

    const loadingContent = (
      <div className="ui list">
        <div className="item">
          <DatabaseFilter
            isFetching
            placeholder="Loading..."
            onFilterChange={() => {}}
          />
        </div>
      </div>
    );

    const fullConent = (
      <div className="ui list" style={cssStyleItems}>
        <div className="item" style={cssStyleItems}>
          <DatabaseFilter
            ref={ref_filter}
            value={filter}
            isFetching={!isMetadataLoad}
            onFilterChange={onFilterChange}
          />
        </div>
        <DatabaseListItemMetatada
          title="Tables"
          client={client}
          items={filteredTables || tables}
          columnsByTable={columnsByTable}
          triggersByTable={triggersByTable}
          indexesByTable={indexesByTable}
          database={database}
          onExecuteDefaultQuery={onExecuteDefaultQuery}
          onExecuteEditTable={onExecuteEditTable}
          onSelectItem={onSelectTable}
          onGetSQLScript={onGetSQLScript}
        />
        <DatabaseListItemMetatada
          collapsed
          title="Views"
          client={client}
          items={filteredViews || views}
          database={database}
          onExecuteDefaultQuery={onExecuteDefaultQuery}
          onGetSQLScript={onGetSQLScript}
        />
        <DatabaseListItemMetatada
          collapsed
          title="Functions"
          client={client}
          items={filteredFunctions || functions}
          database={database}
          onGetSQLScript={onGetSQLScript}
        />
        <DatabaseListItemMetatada
          collapsed
          title="Procedures"
          client={client}
          items={filteredProcedures || procedures}
          database={database}
          onGetSQLScript={onGetSQLScript}
        />
      </div>
    );

    return isCurrentDB && !isMetadataLoad ? loadingContent : fullConent;
  }

  const renderHeader=(isMetadataLoad)=> {
    const { database } = props;

    const collapseCssClass =
      !isMetadataLoad || state.collapsed ? 'right' : 'down';

    return (
      <span
        className="header"
        onDoubleClick={() => onHeaderDoubleClick(database)}
        onContextMenu={(e)=>{
          console.log("onContextmenu")
          e.preventDefault();
          setState((state)=>({...state,x:e.clientx,y:e.clienty}));
          toggleMenu(true);
        }}
        style={STYLE.database}
        >
        <ControlledMenu {...menuProps} 
           anchorPoint={{x:state.x,y:state.y}}
           onClose={()=>toggleMenu(false)}>
            <MenuItem onClick={()=>{
              console.log("preview click")
              props.onShowDiagramModal(props.database)
            }}>ShowDiagramModal</MenuItem>
            <MenuItem>copy</MenuItem>
        </ControlledMenu>
        <i
          className={`${collapseCssClass} triangle icon`}
          style={{ cursor: 'pointer' }}
          onClick={() => onHeaderDoubleClick(database)}
        />
        <i className="database icon" />
        {database.name}
      </span>
    );
  }


    // console.log("DatabaseListItem render")
    // console.log(state);
    const { database, currentDB } = props;

    const isMetadataLoad = isMetadataLoaded(props);
    const isCurrentDB = currentDB === database.name;

    let styleComponent = {};
    if (isCurrentDB) {
      styleComponent = STYLE.activeDatabase;
    } else if (isMetadataLoad) {
      styleComponent = STYLE.loadedDatabase;
    }

    return (
      <div
        className={`item ${isCurrentDB ? 'active' : ''}`}
        style={styleComponent}
      >
        {renderHeader(isMetadataLoad)}
        {renderBody(isMetadataLoad, isCurrentDB)}
      </div>
    );
}

